package com.zzy.furns.filter;

import com.google.gson.Gson;
import com.zzy.furns.domain.Member;
import com.zzy.furns.utils.DataUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings({"all"})
public class AutoFilter implements Filter {

    private List<String> releasePath = new ArrayList<>();
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String releasePathStr = filterConfig.getInitParameter("releasePath");
        String[] split = releasePathStr.split(",");
        for (String path : split) {
            releasePath.add(path);
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        String servletPath = req.getServletPath();

        //如果是访问首页、会员登陆、分页浏览请求，则放行
        for (String path : releasePath) {
            if (servletPath.equals(path)){
                //放行
                filterChain.doFilter(servletRequest,servletResponse);
                return;
            }
        }

        //访问其他资源，判断用户是否登陆
        Member member = (Member) req.getSession().getAttribute("member");
        String loginAdmin = (String) req.getSession().getAttribute("loginAdmin");

        if (loginAdmin != null){
            //管理员登陆
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        Map<String, Boolean> map = new HashMap<>();
        if (member == null){
            //用户没有登陆 重定向登陆界面
            //判断请求是否为Ajax请求
            String Ajax = req.getHeader("X-Requested-With");
            if (Ajax == null){
                //不是Ajax请求
                resp.sendRedirect("/jiaju/views/member/login.jsp");
                return;
            }
            //使Ajax请求
            map.put("needLogin",true);
            DataUtils.sendJSON(map,resp);
            return;
        }

        //用户已登陆 放行
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
